const helper = new Helper(this);
const prefix = helper.getVariable('environmentType');
// 基础服务
const basicRequest = BasicServices?.getInstance(prefix);
// 流媒体服务
const streamRequest = StreamServices?.getInstance(prefix);
// 应急服务
const emergencyRequest = EmergencyServices?.getInstance(prefix);
// 物联 service
const iotServiceRequest = IotServiceServices?.getInstance(prefix);
// 融合通讯
const communicateRequest = CommunicateServices?.getInstance(prefix);


helper.log('页面初始化前')

window.__artemis__tabs = {
    /**
     * { 1: 机构, 2: 群组, 3: 通讯 }
     */
    tabCheckedNum: 1,
    /**
     * 获取按钮组件
     *
     * @return {{all: *, offline: *, online: *}}
     */
    getAllBtn () {
        try {
            return [helper.get('org_btn'), helper.get('group_btn'), helper.get('device_btn')]
        } catch (e) {
            console.error(e);
        }

    },
    /**
     * 设置选中
     *
     * @param active
     */
    setActive(active) {
        $(active.__box).css("box-shadow", "inset 0 -5px 8px var(--active-color)");
    },

    /**
     * 取消选中
     *
     * @param unActive
     */
    setUnActive(unActive) {
        $(unActive.__box).css("box-shadow", "inset 0 0 5px var(--body-bg)");
    },

    /**
     * 选中对用按钮
     * 隐藏其他按钮
     *
     * @param widgetAliasName
     */
    active(widgetAliasName) {
        const allTabs = __artemis__tabs.getAllBtn();
        allTabs.forEach(item => {
            if (item.base?.alias === widgetAliasName) {
                __artemis__tabs.setActive(item)
            } else {
                __artemis__tabs.setUnActive(item)
            }
        });
    },
}


const __renderTree = (artemis, dataSource, callback) => {
    // checkbox { 全部 | 在线 }
    const select = __artemis__tree.getCheckedStatus('search_input');
    let __data = dataSource.map(window.__artemis__tree.breakDataSource);
    if (select === 'all') {
        callback && callback(artemis.resetUsersStatus(__data))
    } else {
        callback && callback(artemis.filterUsersOnline(__data))
    }
}

window.__artemis__tree = {
    /**
     * 获取搜索条件
     *
     * @return {*|string|jQuery}
     */
    getSearchText () {
        const searchInputWidget = helper.get('search_input');
        return $(searchInputWidget?.__box).find('.input-filter').val();
    },
    /**
     * 获取选中状态
     * checkbox { 全部 | 在线 }
     *
     * @return {*}
     */
    getCheckedStatus () {
        return helper.get('type_selection')?.widgetObj?.getChecked()?.value;
    },

    /**
     * 重写用户数据
     *
     * @param member
     * @param index
     * @return {*&{treeId: *, type: string, title: string, userId, username: string}}
     */
    resetMember (member, index) {
        return {
            ...member,
            type: '1',
            title: `${member.personName || member.communicationName || `匿名${index}`}(${member.account})`,
            username: `${member.personName || member.communicationName || `匿名${index}`}`,
            userId: member.account,
            treeId: member.id || member.personId,
        }
    },

    /**
     * 生成随机数
     *
     * @param num
     * @return {number}
     */
    random (num = 10) {
        return parseInt(Math.random() * Math.pow(10, num))
    },

    /**
     * 重组数据结构
     *
     * @param item
     * @return {*}
     */
    breakDataSource (item) {
        if(item.pointId || item.communicationName || item.personName) {
            const { typeCode, communicationName, personName, username } = item;
            item.id = item.personId;
            item.userId = item.account || item.communicationAccount;
            item.username = item.communicationName || item.personName;
            item.title = (communicationName || username || personName) + `(${item.userId})`;
            item.treeId = item.userId;
            item.disabled = true
        } else if(item.orgId || item.orgName) {
            item.title = `${item.orgName}[${item.count}]`;
            item.id = item.orgId;
            item.treeId = item.orgId;
        } else if (item.deptId || item.deptName) {
            item.title = `${item.deptName}[${item.count}]`;
            item.id = item.deptId;
            item.treeId = item.deptId;
        } else if (item.distributionGroupId || item.distributionGroupName) {
            item.title = `${item.distributionGroupName}[${item.count}]`;
            item.id = item.distributionGroupId;
            item.treeId = item.distributionGroupId;
        } else if (item.equipmentTypeName || item.equipmentTypeCode) {
            item.title = `${item.equipmentTypeName}[${item.count}]`;
            item.id = item.equipmentTypeCode;
            item.treeId = item.equipmentTypeCode;
        }

        const setChild = (children) => {
            if (children?.length) {
                const __children = children.map(__artemis__tree.breakDataSource);
                if (item.children) {
                    item.children = [...item.children, ...__children]
                } else {
                    item.children = __children
                }
            }
        }

        if (item.__children) {
            item.type = '0'
            item.children = item.__children?.map(__artemis__tree.breakDataSource)
        }

        // 组织机构
        // if (item.orgList?.length) item.children = item.orgList.map(__artemis__tree.breakDataSource)
        setChild(item.orgList)
        // 群组
        // if (item.groupList?.length) item.children = item.groupList.map(__artemis__tree.breakDataSource)
        setChild(item.groupList)
        // 用户列表
        // if (item.personList?.length) item.children = item.personList.map(__artemis__tree.breakDataSource)
        setChild(item.personList)
        // 通讯账号
        // if (item.accountData?.length) item.children = item.accountData.map(__artemis__tree.breakDataSource)
        setChild(item.accountData)
        // 设备列表
        // if (item.equipmentType?.length) item.children = item.equipmentType.map(__artemis__tree.breakDataSource)
        setChild(item.equipmentType)

        // 调度台
        const dispatchLength = item.dispatchList?.length
        if (dispatchLength) {
            const id = `${__artemis__tree.random(10)}-${__artemis__tree.random(10)}`;
            item.children.unshift({
                id,
                treeId: id,
                title: `调度台[${dispatchLength}]`,
                children: item.dispatchList.map(__artemis__tree.resetMember),
            })
        }

        return item
    },

    /**
     * 渲染树
     *
     * @param dataSource
     * @param callback
     */
    renderTree (dataSource, callback) {
        const artemis = helper.get('三维组件')?.widgetObj.artemis;

        if (artemis) {
            __renderTree(artemis, dataSource, callback)
        }

        /**
         * 在 tree 没有加载时，使用此函数缓存树；
         * 在 tree 加载完成后，调用此函数重新渲染。
         */
        if (!window.__artemisListens) window.__artemisListens = new Set()
        window.__artemisListens.add((artemis) => __renderTree(artemis, dataSource, callback))
    },

    deepCopy (dataSource) {
        return dataSource.map(item => {
            if (Array.isArray(item.children)) {
                item.__children = __artemis__tree.deepCopy([...item.children])
            }
            if (Array.isArray(item.orgList)) {
                item.orgList = __artemis__tree.deepCopy(item.orgList)
            }
            if (Array.isArray(item.groupList)) {
                item.groupList = __artemis__tree.deepCopy(item.groupList)
            }
            if (Array.isArray(item.personList)) {
                item.personList = __artemis__tree.deepCopy(item.personList)
            }
            if (Array.isArray(item.accountData)) {
                item.accountData = __artemis__tree.deepCopy(item.accountData)
            }
            if (Array.isArray(item.equipmentType)) {
                item.equipmentType = __artemis__tree.deepCopy(item.equipmentType)
            }
            return item
        })
    },

    /**
     * 加载组织机构
     */
    loadOrgListData (params) {
        return communicateRequest.getOrgListByName(params).then((result) => {
            if (Array.isArray(result)) return __artemis__tree.deepCopy(result)
        })
    },

    /**
     * 加载群组
     */
    loadGroupListData (params) {
        return communicateRequest.getGroupListByName(params).then((result) => {
            if (Array.isArray(result)) return __artemis__tree.deepCopy(result)
        })
    },

    /**
     * 加载通讯账号
     */
    loadAccountListData (body) {
        return communicateRequest.getAllAccountByEquipment(body).then((result) => {
            if (Array.isArray(result)) return __artemis__tree.deepCopy(result)
        })
    },
}

